package com.glorysoft.tonglingxjpda.ui.function.viewmodel

import com.glorysoft.tonglingxjpda.base.BaseViewModel
import com.glorysoft.tonglingxjpda.entity.EdcEntity
import com.glorysoft.tonglingxjpda.entity.EdcSetItemLineListEntity
import com.glorysoft.tonglingxjpda.entity.TempDataEntity
import com.glorysoft.tonglingxjpda.entity.ui.ToastMessageBean
import com.glorysoft.tonglingxjpda.model.TaskRepository
import com.glorysoft.tonglingxjpda.ui.function.adapter.DataCollectionAdapter
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser

/**
 * FileName: DataCollectionViewModel
 * Author: XJH
 * Date: 2022/5/6 17:25
 * Description:
 * History:
 */
class DataCollectionViewModel : BaseViewModel() {

    private val trackRepository = TaskRepository()
    var edcInfo : EdcEntity? = null
    val mAdapter = DataCollectionAdapter(null)


    fun getEdcData(batchID: String?, lotid: String?) {
        val map = JsonObject()
        map.addProperty("ACTIONTYPE","LOTGETEDCITEM")
        map.addProperty("BATCHID",batchID)
        map.addProperty("LOTID",lotid)
        launchOnlyResult({
            edcInfo = trackRepository.getEdcInfo(map)
            if (edcInfo?.EDCSETLIST!!.isNotEmpty()){
                if (edcInfo!!.EDCSETLIST[0].EDCSETITEMLINELIST.isNotEmpty()){
                    mAdapter.setNewData(edcInfo!!.EDCSETLIST[0].EDCSETITEMLINELIST)
                }
            }
        })
    }

    fun saveEdcData(showTemp : Boolean){
        if (!showTemp){
            edcInfo!!.EDCSETLIST[0].EDCSETITEMLINELIST.forEach{ lineIt ->
                if (lineIt.ISMANDATORY){
                    lineIt.EDCSETBINLINEVALUELIST.forEach {
                        if (it.VALUE.isEmpty()){
                            defUI.toastEvent.value = ToastMessageBean("采集项${lineIt.DESCRIPTION}.有必填项未完成",false)
                            return
                        }
                    }
                }
            }
        }
        val map = JsonObject()
        map.addProperty("ACTIONTYPE","LOTEDCREPORT")
        map.addProperty("BATCHID",edcInfo?.BATCHID)
        map.addProperty("LOTID",edcInfo?.LOTID)
        map.addProperty("PARTNAEM",edcInfo?.PARTNAME)
        map.addProperty("STEPNAME",edcInfo?.STEPNAME)
        map.addProperty("ISTEMP",showTemp)
        map.add("EDCSETLIST", JsonParser().parse(Gson().toJson(edcInfo?.EDCSETLIST)).asJsonArray)
        launchOnlyResult({
            trackRepository.getEdcInfo(map)
            defUI.startActivity.call()

        })
    }
}